package io.p2p.stream.turn.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.turn.protocol.TcpProtocolManagerFactory;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class TurnTcpServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("Received JSON data: {}",msg);

        try {
            JSONObject jsonObject = JSON.parseObject(msg);

            if (jsonObject.containsKey("type")) {
                String protocol = jsonObject.get("type").toString();
                TcpProtocolManagerFactory.getHandler(protocol)
                        .process(ctx, (InetSocketAddress) ctx.channel().remoteAddress(), jsonObject);
            }
        }catch(Exception e){
            log.error("TCP Handling exceptions: " + e.getMessage());
            exceptionCaught(ctx,e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
